<?php
/**
 * 菜单逻辑模块
 * @author Paco
 * @date  2017-07-29
 */

namespace app\common\logic;

use arrayset\Arrayset;

class PermissionLogic
{
    private $admin_m;
    private $role_m;
    private $rule_m;
    private $ar_m;
    private $array_c;

    public function __construct()
    {
        $this->admin_m = model("admin");
        $this->role_m  = model("role");
        $this->rule_m  = model("rule");
        $this->ar_m    = model("ar");
        $this->array_c = new Arrayset();
    }

/************************************************管理员部份**************************************/
    /**
     * 管理员列表
     * @return [type] [description]
     */
    public function getAdminList($params = [])
    {
        $keyword = "";
        $page    = 2000;
        if (isset($params['keyword'])) {
            $keyword = $params['keyword'];
        }
        if (isset($params['pagesize'])) {
            $page = $params['pagesize'];
        }
        $rs = $this->admin_m->getAdmins($keyword, $page);
        if ($rs['data']) {
            $ar_m = model("ar");
            foreach ($rs['data'] as $key => $v) {
                $role = $ar_m->getRoleId($v['id']);
                //$role = implode(",",$role);
                $rs['data'][$key]["roles"] = $role;
            }
        }
        $data['pages']        = $rs['last_page'];
        $data['total']        = $rs['total'];
        $data['data']['list'] = $rs['data'];
        return $data;
    }

    public function addAdmin($data)
    {
        $arr      = [];
        $validate = validate('AdminValidate');
        if (!$validate->check($data)) {
            $arr['msg'] = $validate->getError();
        } else {
            unset($data['pwd2']);

            $ar = [];
            if (isset($data['roles'])) {
                $ar = $data['roles'];
                unset($data['roles']);
            }

            $this->admin_m::startTrans();
            try {
                $id = $this->admin_m->saveAdmin($data);

                if ($ar) {
                    foreach ($ar as $k => $v) {
                        $ar_data[$k]['uid']      = $id;
                        $ar_data[$k]['group_id'] = $v;
                    }

                    $this->ar_m->saveAr($ar_data);
                }

                // 提交事务
                $this->admin_m::commit();

                $arr['status']     = 200;
                $arr['msg']        = "操作成功";
                $arr['data']['id'] = $id;

            } catch (\Exception $e) {
                // 回滚事务
                $this->admin_m::rollback();
                $arr['msg'] = "操作失败";
            }
        }
        return $arr;
    }

    public function saveAdmin($data)
    {
        $arr   = [];
        $where = [];
        if (isset($data["id"])) {
            $where["id"] = $data['id'];
            unset($data['id']);
        }

        $ar = [];
        if (isset($data['roles'])) {
            $ar = $data['roles'];
            unset($data['roles']);
        }

        $validate = validate('AdminValidate');

        if (!$validate->scene('edit')->check($data)) {
            $arr['msg'] = $validate->getError();
        } else {
            if (isset($data['pwd']) && $data['pwd'] == "") {
                unset($data['pwd']);
                unset($data['pwd2']);
            } else {
                if (isset($data['pwd'])) {

                    $data['pwd'] = sha1md5($data['pwd']);
                    unset($data['pwd2']);
                }

            }

            $this->admin_m::startTrans();
            try {
                $this->admin_m->saveAdmin($data, $where);

                if ($ar) {
                    $this->ar_m->delAr(["uid" => $where["id"]]);
                    foreach ($ar as $k => $v) {
                        $ar_data[$k]['uid']      = $where["id"];
                        $ar_data[$k]['group_id'] = $v;
                    }

                    $this->ar_m->saveAr($ar_data);
                }

                // 提交事务
                $this->admin_m::commit();

                $arr['status']     = 200;
                $arr['msg']        = "操作成功";
                $arr['data']['id'] = $where["id"];

            } catch (\Exception $e) {
                // 回滚事务
                $this->admin_m::rollback();
                $arr['msg'] = "操作失败";
            }

        }
        return $arr;
    }

    public function delAdmin($id)
    {
        $id = explode(",", $id);
        if ($this->admin_m->delAdmin($id)) {
            $rs['msg']    = "操作成功";
            $rs['status'] = 200;
        } else {
            $rs['msg'] = "操作失败";
        }

        return $rs;
    }

/*******************************角色模块********************************/

    public function getRoles($params = [])
    {
        $page = 2000;
        if (isset($params['pagesize'])) {
            $page = $params['pagesize'];
            unset($params['pagesize']);
        }
        $roles                = $this->role_m->getRoles($params);
        $data['pages']        = $roles['last_page'];
        $data['total']        = $roles['total'];
        $data['data']['list'] = $roles['data'];
        return $data;
    }

    public function saveRole($params)
    {
        if (isset($params['rules'])) {
            $params['rules'] = implode(",", $params['rules']);
        }

        $validate = validate('RoleValidate');

        if (isset($params["id"])) {
            $where['id'] = $params["id"];
            unset($params["id"]);

            if ($this->role_m->saveRole($params, $where)) {
                $arr['msg']    = "操作成功";
                $arr['status'] = 200;
            } else {
                $arr['msg'] = "操作失败";
            }

        } else {
            if (!$validate->check($params)) {
                $arr['msg'] = $validate->getError();
            } else {
                if ($id = $this->role_m->saveRole($params)) {
                    $arr['msg']        = "操作成功";
                    $arr['status']     = 200;
                    $arr['data']['id'] = $id;
                } else {
                    $arr['msg'] = "操作失败";
                }
            }
        }
        return $arr;
    }

    public function delRole($id)
    {
        $id = explode(",", $id);
        if ($this->role_m->delRole($id)) {
            $rs['msg']    = "操作成功";
            $rs['status'] = 200;
        } else {
            $rs['msg'] = "操作失败";
        }
        return $rs;
    }

/***************************************权限模块*******************************/

    public function getRule()
    {

        //取得所有规则
        $rule               = $this->rule_m->getRules();
        $rule               = $this->array_c->getTree($rule);
        $rs['data']['list'] = $rule;
        return $rs;
    }

    public function getTreeRules()
    {
        //取得所有规则
        $rule               = $this->rule_m->getRules();
        $rule               = $this->array_c->getTree($rule);
        $rule               = $this->array_c->setArrayKey($rule);
        $rule               = $this->array_c->getDeepTree($rule);
        $rs['data']['list'] = $rule;
        return $rs;
    }

    public function addRule($data)
    {
        $arr      = [];
        $validate = validate('RuleValidate');
        if (!$validate->check($data)) {
            $arr['msg'] = $validate->getError();
        } else {
            if ($id = $this->rule_m->saveRule($data)) {
                $arr['status']     = 200;
                $arr['msg']        = "操作成功";
                $arr['data']['id'] = $id;
            } else {
                $arr['msg'] = "操作失败";
            }
        }
        return $arr;
    }

    public function saveRule($data)
    {
        $arr   = [];
        $where = [];

        if (isset($data['name'])) {
            $validate = validate('RuleValidate');
            if (!$validate->scene("edit")->check($data)) {
                $arr['msg'] = $validate->getError();
                return $arr;
            }
        }
        if (isset($data["id"])) {

            //当更新状态时
            if (isset($data['status'])) {
                $rule = $this->rule_m->getRules();
                $rule = $this->array_c->setArrayKey($rule);

                //如果为开启状态，需判断父级是否是开启，若不是不能开启
                if ($data['status']) {
                    if ($rule[$data['id']]['pid']) {
                        if (!$rule[$rule[$data['id']]['pid']]['status']) {
                            $arr['msg'] = "请先启用父类:" . $rule[$rule[$data['id']]['pid']]['title'];
                        }
                    }
                } else {
                    foreach ($rule as $key => $v) {
                        if ($v['pid'] == $data['id']) {

                            if ($v['status']) {
                                $arr['msg'] = "请先关闭子类:" . $v['title'];
                                break;
                            }
                        }
                    }
                }

                if (isset($arr['msg'])) {
                    return $arr;
                }
            }

            $where["id"] = $data['id'];
            unset($data['id']);

        }

        if ($id = $this->rule_m->saveRule($data, $where)) {
            $arr['status']     = 200;
            $arr['msg']        = "操作成功";
            $arr['data']['id'] = $id;
        } else {
            $arr['msg'] = "操作失败";
        }

        return $arr;
    }

    public function delRule($id)
    {
        $id = explode(",", $id);
        if ($this->rule_m->delRule($id)) {
            $rs['msg']    = "操作成功";
            $rs['status'] = 200;
        } else {
            $rs['msg'] = "操作失败";
        }
        return $rs;
    }

}
